#include <windows.h>

#include "lib.h"
#include "dialog.h"
#include "systemfont.h"

Dialog::Dialog(HWND hParent, HINSTANCE hInstance)
{
	m_hParent	= hParent;
	m_hDialog	= (HWND)0;
	m_hInstance	= hInstance;
	m_result	= -1;
}

Dialog::~Dialog()
{
	if (m_hDialog)
	{
		DestroyWindow(m_hDialog);
		m_hDialog = (HWND)0;
	}
}

BOOL
Dialog::dialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
		case WM_DESTROY:
			SetWindowLong(m_hDialog, DWL_USER, 0);
			m_hDialog = (HWND)0;
			break;
	}

	return FALSE;
}

// Case 10493:   Greek Characters Not Appearing 
//
// Greek characters were appearing as rectangles in
// dialogs that did not use the TextBlock class.  The
// workaround is to set the font for all dialog
// controls.

class AutoDialogFont
{
public:
	~AutoDialogFont()
	{
		if ( hFont )
		{
			DeleteObject( hFont );
			hFont = NULL;
		}
	}

	static HFONT getDialogFont()
	{
		if ( !hFont )
		{
			LOGFONT lf;
			lf.lfHeight = -9;
			lf.lfWidth = 0;
			lf.lfEscapement = 0;
			lf.lfOrientation = 0;
			lf.lfWeight = FW_NORMAL;
			lf.lfItalic = 0;
			lf.lfUnderline = 0;
			lf.lfStrikeOut = 0;
			lf.lfCharSet = ANSI_CHARSET;
			lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
			lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
			lf.lfQuality = DEFAULT_QUALITY;
			lf.lfPitchAndFamily = VARIABLE_PITCH | FF_ROMAN;
			lstrcpy(lf.lfFaceName, SystemFont::fontName(SYSFONT_SANSSERIF));
			hFont = CreateFontIndirect(&lf);	
		}

		return hFont;
	}

private:
	static HFONT hFont;
} theAutoDialogFont;

HFONT AutoDialogFont::hFont = NULL;

//
BOOL CALLBACK EnumWindowsProc_SetFont( HWND hWnd, LPARAM lParam )
{
	HFONT hFont = (HFONT) lParam;
	if ( hFont )
	{
		SendMessage( hWnd, WM_SETFONT, (WPARAM) hFont, 0 );
	}

	return TRUE;
}

static void SetDialogFont( HWND hWnd )
{
	HFONT hFont = AutoDialogFont::getDialogFont();
	EnumWindowsProc_SetFont( hWnd, (LPARAM) hFont );
	EnumChildWindows( hWnd, EnumWindowsProc_SetFont, (LPARAM) hFont );
}

BOOL FAR PASCAL
Dialog::topDialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	Dialog * This;

	if (uMsg == WM_INITDIALOG)
	{
		RECT rc, rcDlg, rcParent;
		HWND hParent;

		SetWindowLong(hWnd, DWL_USER, (LONG)lParam);
		This = (Dialog *)lParam;
		This->m_hDialog = hWnd;

		///////////////////////////////////////////////////////////////////////////
		// get message font
		SetDialogFont( hWnd );

		// center dialog within parent
		//
		hParent = GetParent(hWnd);
		if (hParent == (HWND)0)
			hParent = GetDesktopWindow();
		GetWindowRect(hParent, &rcParent);
		GetWindowRect(hWnd, &rcDlg);
		CopyRect(&rc, &rcParent);
		OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
		OffsetRect(&rc, -rc.left, -rc.top);
		OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
		SetWindowPos(hWnd, HWND_TOP,
			rcParent.left + (rc.right >> 1),
			rcParent.top + (rc.bottom >> 1),
			0, 0, SWP_NOSIZE);
	}
	else
		This = (Dialog*)GetWindowLong(hWnd, DWL_USER);

	if (This)
		return This->dialogProc(hWnd, uMsg, wParam, lParam);
	else
		return FALSE;
}
